import React, { useEffect, useState } from 'react';
import { Tree } from 'antd';
import produce from 'immer';
import Ellipsis from '@/zero/components/Ellipsis';
import styles from './index.less';

const TreeNodeElement = Tree.TreeNode;

const renderTreeNodes = (newProps = {}) => {
  const {
    treeNodes = [],
    titleKey = 'title',
    treeNodeKey = 'id',
    childrenKey = 'children',
    ellipsisExtOption = {
      disabled: false,
      length: 25,
    },
    renderTreeNodeTitle = (text) => (
      <Ellipsis tooltip={false} title={text} {...ellipsisExtOption}>
        {text}
      </Ellipsis>
    ),
  } = newProps;

  return treeNodes
    .filter((item) => Object.keys(item).length !== 0)
    .map((item) => {
      const {
        [`${titleKey}`]: titleValue,
        [`${treeNodeKey}`]: newKey,
        [`${childrenKey}`]: childrenValue,
        ...rest
      } = item;
      const newTreeNodeTitle = renderTreeNodeTitle(titleValue);

      const uniqueKey = newKey && `${newKey}`;

      if (childrenValue) {
        return (
          <TreeNodeElement {...rest} key={uniqueKey} value={uniqueKey} title={newTreeNodeTitle}>
            {renderTreeNodes({ ...newProps, treeNodes: childrenValue })}
          </TreeNodeElement>
        );
      }
      return (
        <TreeNodeElement {...rest} key={uniqueKey} value={uniqueKey} title={newTreeNodeTitle} />
      );
    });
};

const Index = (props) => {
  const newProps = {
    type: 'Tree', // 控件类型 => Tree, DirectoryTree

    showLine: true, // 是否展示连接线

    checkable: true, // 节点前添加 Checkbox 复选框

    defaultExpandAll: true, // 默认展开所有树节点
    treeNodes: [
      {
        id: '0',
        title: '全部分类',
        children: [
          {
            id: '1',
            title: '分类1',
            children: [
              {
                id: '11',
                title: '子分类1-1',
              },
              {
                id: '12',
                title: '子分类1-2',
              },
            ],
          },
          {
            id: '2',
            title: '分类2',
            children: [
              {
                id: '21',
                title: '子分类2-1',
              },
              {
                id: '22',
                title: '子分类2-2',
              },
            ],
          },
        ],
      },
    ],

    ...props,
  };

  const { type, defaultExpandAll, treeNodes } = newProps;

  const finalProps = produce(newProps, (draftState) => {
    const {
      value,
      onChange,

      checkable,

      defaultCheckedKeys,
      checkedKeys,
      defaultSelectedKeys,
      selectedKeys,
    } = draftState;

    if (checkable) {
      if (!defaultCheckedKeys) {
        draftState.checkedKeys = (checkedKeys || value)?.map((item) => (item ? `${item}` : null));
      }
      draftState.onCheck = (newCheckedKeys, info) => {
        if (onChange) {
          onChange(newCheckedKeys, info);
        }
      };
    } else {
      if (!defaultSelectedKeys) {
        draftState.selectedKeys = (selectedKeys || value)?.map((item) => (item ? `${item}` : null));
      }
      draftState.onSelect = (newSelectedKeys, info) => {
        if (onChange) {
          onChange(newSelectedKeys, info);
        }
      };
    }
    return draftState;
  });

  const [timestamp, setTimestamp] = useState('19491001');

  useEffect(() => {
    if (defaultExpandAll && treeNodes && treeNodes.length !== 0) {
      setTimestamp(`${Date.now()}`);
    }
  }, [treeNodes]);

  return (
    <span className={styles.col24} key={timestamp}>
      {type === 'Tree' && (
        <Tree {...finalProps} multiple={false}>
          {renderTreeNodes(finalProps)}
        </Tree>
      )}
      {type === 'DirectoryTree' && (
        <Tree.DirectoryTree expandAction="doubleClick" {...finalProps} multiple={false}>
          {renderTreeNodes(finalProps)}
        </Tree.DirectoryTree>
      )}
    </span>
  );
};

Object.keys(Tree).forEach((item) => {
  if (!['defaultProps'].includes(item)) {
    Index[item] = Tree[item];
  }
});
Index.displayName = 'Tree';
export default Index;
